<!DOCTYPE html 
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Actualizar Evento</title>
    <link rel="stylesheet" type="text/css" media="all" href="skins/aqua/theme.css" title="Aqua" />
    <style>
    li {
      border-bottom: solid black 1px;      
      margin: 10px; 
      padding: 2px; 
      width: auto;
      padding-bottom: 20px;
    }
    h2 {
      color: red; 
      text-decoration: none;  
    }
    span.attr {
      font-weight: bolder;  
    }
	.Estilo4 {
	color: #990000;
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 2;
	font-weight: bold;
}
.Estilo8 {
	color: #000000;
	font-family: Verdana, Arial, Helvetica, sans-serif;

}
.Estilo5 {
	color: #000000;
	font-size: 14px;
}
.Estilo6 {color: #FF0000}
.Estilo7 {color: #FF0000; }
}
    </style> 
<!-- import the calendar script -->
<script type="text/javascript" src="calendar.js"></script>

<!-- import the language module -->
<script type="text/javascript" src="lang/calendar-en.js"></script>
 
<script type="text/javascript">function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    cal.callCloseHandler();
}
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use
  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

function showFlatCalendar() {
  var parent = document.getElementById("display");
  var cal = new Calendar(0, null, flatSelected);
  cal.weekNumbers = false;

  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");

  cal.create(parent);

  cal.show();
}

function compare_dates(fecha, fecha2){  
    var xMonth=fecha.substring(3, 5);  
    var xDay=fecha.substring(0, 2);  
    var xYear=fecha.substring(6,10);  
    var yMonth=fecha2.substring(3, 5);  
    var yDay=fecha2.substring(0, 2);  
    var yYear=fecha2.substring(6,10);  
    if (xYear> yYear){  
        return(true)  
    }  
    else{  
      if (xYear == yYear){   
        if (xMonth> yMonth){  
            return(true)  
        }  
        else{   
          if (xMonth == yMonth){  
            if (xDay> yDay)  
              return(true);  
            else  
              return(false);  
          }  
          else  
            return(false);  
        }  
      }  
      else  
        return(false);  
    }  
}  

function validar(){
	var msj = "false";
	var dia, mes, anio,fecha;
	if(document.form.title.value == ""){
		alert("Debe ingresar la Descripción.");
		msj="true";
		return false;
	} 
	
	if(document.form.title.value == ""){
		alert("Debe ingresar el Contenido.");
		msj="true";
		return false;
	}  
	if(document.form.title.value != "" && document.form.title.value.length <= 10){
		alert("Debe ingresar por lo menos quince caracteres en la Descripción");
		msj="true";	
		return false;
	}
	if(document.form.fecfin.value == ""){
		alert("Debe Ingresar la Fecha Fin de Publicación.");
		msj="true";
		return false;
	} 
	if(document.form.fecini.value == ""){
		alert("Debe Ingresar la Fecha de Inicio de Publicación.");
		msj="true";
		return false;
	}
	
	if (compare_dates(document.form.fecini.value, document.form.fecfin.value)){  
  		alert("La fecha de inicio es mayor a la fecha fin de publicación.");  
		msj="true";
		return false;
	}
	
	if(document.form.sdate_hh.value == "" || document.form.sdate_hh.value <= 0 || document.form.sdate_hh.value > 120 ){
		alert("Debe Ingresar la Hora de la Fecha Inicial Correctamente.");
		msj="true";
		return false;
	}
	if(document.form.sdate_ii.value == "" || document.form.sdate_ii.value < 0 || document.form.sdate_ii.value > 59 ){
		alert("Debe Ingresar los Minutos de la Fecha Inicial Correctamente.");
		msj="true";
		return false;
	}
	if(document.form.edate_hh.value == "" || document.form.edate_hh.value <= 0 || document.form.edate_hh.value > 120){
		alert("Debe Ingresar la Hora Fin de la Fecha Final Correctamente.");
		msj="true";
		return false;
	}
	if(document.form.edate_ii.value == "" || document.form.edate_ii.value < 0 || document.form.edate_ii.value > 59 ){
		alert("Debe Ingresar los Minutos de la Fecha Final Correctamente.");
		msj="true";
		return false;
	}
	if(document.form.sdate_hh.value > document.form.edate_hh.value && document.form.tardeF.value=='am' && document.form.   tardeI.value=='am' && document.form.fecini.value==document.form.fecfin.value){
		alert("La Hora Fecha Inicial es Menor a la Hora fecha Final.");
		msj="true";
		return false;
	}
	if(document.form.sdate_hh.value > document.form.edate_hh.value && document.form.tardeF.value=='pm' && document.form.tardeI.value=='pm' && document.form.fecini.value==document.form.fecfin.value){
		alert("La Hora Fecha Inicial es Menor a la Hora fecha Final.");
		msj="true";
		return false;
	}
	
	
	if(msj == "false"){            		
		document.form.submit();
	}
}
function cancelar(){
	document.form.action = "view.php";
	document.form.submit();
}
</script>
    
    
    
  </head>
  <body>
    <?php
    // load classes
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Gdata');
    Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
    Zend_Loader::loadClass('Zend_Gdata_Calendar');
    Zend_Loader::loadClass('Zend_Http_Client');
    
    // connect to service
    $gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
    $user = "urbalbertoravell@gmail.com";
    $pass = "albertoravell001";
    $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal);
    $gcal = new Zend_Gdata_Calendar($client);
     
    // get event details
    if (!isset($_POST['submit'])) {
      if (isset($_GET['id'])) {
        try {          
          $event = $gcal->getCalendarEventEntry('http://www.google.com/calendar/feeds/default/private/full/' . $_GET['id']);
        } catch (Zend_Gdata_App_Exception $e) {
          echo "Error: " . $e->getResponse();
        }
      } else {
          die('ERROR: No Existe Evento!');  
      }  
      
      // format data into human-readable form
      // populate a Web form with the record
	  	  		  
      $title = $event->title;
      $when = $event->getWhen();
      $startTime = strtotime($when[0]->getStartTime());	  
      $sdate_dd = date('d', $startTime);
	  $sdate_dd = $sdate_dd;
      $sdate_mm = date('m', $startTime);
      $sdate_yy = date('Y', $startTime);
      $sdate_hh = date('H', $startTime);
      $sdate_ii = date('i', $startTime);
	  
      $endTime = strtotime($when[0]->getEndTime());
      $edate_dd = date('d', $endTime);
	  $edate_dd = $edate_dd;
      $edate_mm = date('m', $endTime);
      $edate_yy = date('Y', $endTime);
      $edate_hh = date('H', $endTime);
      $edate_ii = date('i', $endTime);  
	  
	   $tardeI = 'am';
	   $tardeF = 'am';
	  
	  if($sdate_hh > 12)
	  {
	     $sdate_hh = $sdate_hh - 12;
		 $tardeI = 'pm';
	  }
	  if($edate_hh > 12)
	  {
	     $edate_hh = $edate_hh - 12;
		 $tardeF = 'pm';
	  }
  
	     
    ?>
<TABLE height=500 cellSpacing=3 cellPadding=0 width=549 align=center bgColor=#ffffff border=0 bordercolor="#ff0000">
<tr>
<td vAlign=top width=543  height=490 bgColor=#ff0000>
	<TABLE height=500 cellSpacing=1 width=541  border=0>
    <TBODY>
    <TR>
    <TD vAlign=top bgColor=#ffffff width="537">            
          <DIV>
            <p>&nbsp;</p>
            <DIV align=center class="Estilo4">
              <p class="Estilo5">Modificar Eventos</p>
              <p class="Estilo5">&nbsp;</p>
              <p class="Estilo5 Estilo6">_________________________________________________</p>
           </DIV>    
 
            <form name = "form" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" enctype="multipart/form-data">
              <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
              <table align="center">
              
                <tr height="40">
                    <td></td>
                    <td><span class="Estilo6">* </span>Descripci&oacute;n:</td>
                    <td><input name="title" type="text" size="50" value="<?php echo $title; ?>"/></td>
                </tr>
                <tr height="40">
                    <td></td>
                    <td><span class="Estilo6">* </span>Fecha de Inicio: </td>
                    <td><input type="text" name="fecini" id="fecini" size="20" readonly="readonly"                value="<?php echo $sdate_dd; ?>-<?php echo $sdate_mm; ?>-<?php echo $sdate_yy; ?>" ><input type="reset" value=" ... " onclick="return showCalendar('fecini', '%d-%m-%Y');"></td>
                </tr>
                <tr height="40">
                    <td></td>
                    <td><span class="Estilo6">* </span>Hora Inicio(hh:mm):</td>
                    <td><input name="sdate_hh" type="text" size="2" maxlength="2" value="<?php echo $sdate_hh; ?>" 
                    onKeypress="if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;" /> 
                        <input name="sdate_ii" type="text" size="2" maxlength="2" value="<?php echo $sdate_ii; ?>"
                        onKeypress="if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;" />
					<select name="tardeI" id="tardeI">
                        <option value="am" <?php if(!strcmp($tardeI,"am")) echo "selected" ?> >am</option>
                        <option value="pm" <?php if(!strcmp($tardeI,"pm")) echo "selected" ?> >pm</option>
                    </select>	
						</td>
                </tr>
                <tr height="40">
                    <td></td>
                    <td><span class="Estilo6">* </span>Fecha Final:</td>
                    <td><input type="text" name="fecfin" id="fecfin" size="20" readonly="readonly" 
                    value="<?php echo $edate_dd; ?>-<?php echo $edate_mm; ?>-<?php echo $edate_yy; ?>" ><input type="reset" value=" ... " onclick="return showCalendar('fecfin', '%d-%m-%Y');"></td>
                </tr>
                 <tr height="40">
                    <td></td>
                    <td><span class="Estilo6">* </span>Hora Final(hh:mm):</td>
                    <td><input name="edate_hh" type="text" size="2" maxlength="2" onKeypress="if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;" value="<?php echo $edate_hh; ?>" /> 
                        <input name="edate_ii" type="text" size="2" maxlength="2" onKeypress="if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;" value="<?php echo $edate_ii; ?>" />
						<select name="tardeF" id="tardeF">
                        <option value="am" <?php if(!strcmp($tardeF,"am")) echo "selected" ?> selected>am</option>
                        <option value="pm" <?php if(!strcmp($tardeF,"pm")) echo "selected" ?> >pm</option>
                        </select>
						</td>
                </tr>
                <tr height="40">
                    <td></td>
                    <td></td>
                    <td><input width="200" name="submit" type="submit" value="Aceptar" onClick="return validar();"  /> 
                        <input type="submit" name="Cancelar" value="Cancelar"  onClick="return cancelar();"></td>
                </tr>
                 <tr align="left">
                    <td align="left" colspan="3"><span class="Estilo7">Todos los campos con * son obligatorios</span></td>
                </tr>     
            </form>
                </DIV>
           </TD>
          </TR>
        </TBODY>
      </TABLE>
</td>
</tr>
</TABLE>    
    <?php              
    } else {
      // if form submitted
	  
	  
	  // Set de las variables para formato de fecha que requiere el programa
	   
	  $sdate_dd = substr($_POST['fecini'], 0, 2);
	  $sdate_dd = $sdate_dd;
      $sdate_mm = substr($_POST['fecini'], 3, 2);
      $sdate_yy = substr($_POST['fecini'], 6, 4);
      $edate_dd = substr($_POST['fecfin'], 0, 2);
	  $edate_dd = $edate_dd;
      $edate_mm = substr($_POST['fecfin'], 3, 2);
      $edate_yy = substr($_POST['fecfin'], 6, 4);
	  
	   $tardeI = $_POST['tardeI'];
	  $tardeF = $_POST['tardeF'];
	  $sdate_hh = $_POST['sdate_hh'];
	  $edate_hh = $_POST['edate_hh'];
	  if($tardeI == 'pm')
	  	$sdate_hh = $sdate_hh + 12;
	
	  if($tardeF == 'pm')
	     $edate_hh =  $edate_hh + 12;
	  
      // validate input
      if (empty($_POST['id'])) {
        die('ERROR: No Existe el Evento');
      } 
      
      if (empty($_POST['title'])) {
        die('ERROR: Titulo Obligatorio');
      } 
      
      if (!checkdate($sdate_mm, $sdate_dd, $sdate_yy)) {
        die('ERROR: Fecha Inicial Invalida');        
      }
      
      if (!checkdate($edate_mm, $edate_dd, $edate_yy)) {
        die('ERROR: Fecha Final Invalida');        
      }
	  

      $title = htmlentities($_POST['title']);
      $start = date(DATE_ATOM, mktime($sdate_hh, $_POST['sdate_ii'], 0, $sdate_mm, $sdate_dd, $sdate_yy));
      $end = date(DATE_ATOM, mktime($edate_hh, $_POST['edate_ii'], 0, $edate_mm, $edate_dd, $edate_yy));
      
      // get existing event record
      // update event attributes
      // save changes to server
      try {
        $event = $gcal->getCalendarEventEntry('http://www.google.com/calendar/feeds/default/private/full/' . $_POST['id']);
        $event->title = $gcal->newTitle($title); 
        $when = $gcal->newWhen();
        $when->startTime = $start;
        $when->endTime = $end;
        $event->when = array($when);        
        $event->save();   
      } catch (Zend_Gdata_App_Exception $e) {
        die("Error: " . $e->getResponse());
      }
	  ?>
	  <TABLE height=500 cellSpacing=3 cellPadding=0 width=549 align=center bgColor=#ffffff border=0 bordercolor="#ff0000">
<tr>
<td vAlign=top width=543  height=490 bgColor=#ff0000>
	<TABLE height=500 cellSpacing=1 width=541  border=0>
        <TBODY>
        <TR>
          <TD vAlign=top bgColor=#ffffff width="537">            
          <DIV>
          	<DIV>
            <p>&nbsp;</p>
            <DIV align=center class="Estilo4">
              <p class="Estilo5">Modificar Evento</p>
              <p class="Estilo5">&nbsp;</p>
              <p class="Estilo5 Estilo6">_________________________________________________</p>
           </DIV>  
              <table align="center">
                <tr>
                    <td>
                        <img src="../IMAGENES-PROYECTO/modificar.png"></a>
                    </td>
                </tr> 
               </table>
			</DIV>
          </TD>
          </TR>
          </TBODY>
          </TABLE>
    </td>
    </tr>
  </TABLE>
      <?php
	  echo "<meta http-equiv='refresh' content='1; url=../Eventos/view.php' />";
    }    
    ?>    
  </body>
</html>     
